//
//  MYGHomeMoreController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/6.
//

import UIKit
import SwifterSwift
struct MYGHomeToolsItem {
    var type: MYGHomeToolsType
    var isHome: Bool
    var changeAction: (()->Void)?
    
    var image: String {
        type.image
    }
    var name: String {
        type.name
    }
    var action: (()->Void)? {
        type.action
    }
}
struct MYGHomeToolsSeciton {
    var name: String
    var items: [MYGHomeToolsItem] = []
}
enum MYGHomeToolsType: Int {
    case bodyImage = 0
    case operation
    case teamManage
    case medical
    case addmi
    case level
    case study
    case course
    case tipsCircle
    case profeInfo
    case profeTeam
    case find
    case project
    case patient
    case clinTry
    case docu
    case report
    case vitae
    case more
    case clouldDisk

    var name: String {
        switch self {
        case .bodyImage:
            return "随身影像"
        case .operation:
            return "手术记录"
        case .teamManage:
            return "团队管理"
        case .medical:
            return "医学公式"
        case .clouldDisk:
            return "我的云盘"
        case .addmi:
            return "入院管理"
        case .level:
            return "分级诊疗"
        case .study:
            return "学术会议"
        case .course:
            return "培训课程"
        case .tipsCircle:
            return "话题圈子"
        case .profeInfo:
            return "行业资讯"
        case .profeTeam:
            return "行业协会"
        case .find:
            return "发现"
        case .project:
            return "项目管理"
        case .patient:
            return "患者管理"
        case .clinTry:
            return "临床试验"
        case .docu:
            return "文献查询"
        case .report:
            return "我的报道"
        case .vitae:
            return "完美简历"
        case .more:
            return "问问"
        }
    }
    
    var image: String {
        switch self {
        case .bodyImage:
            return "MYG_home_bodyImage"
        case .operation:
            return "MYG_home_operationRecord"
        case .teamManage:
            return "MYG_home_teamManage"
        case .medical:
            return "MYG_home_medical"
        case .clouldDisk:
            return "MYG_home_clouldDisk"
        case .addmi:
            return "MYG_home_addmiManage"
        case .level:
            return "MYG_home_levelManage"
        case .study:
            return "MYG_home_study"
        case .course:
            return "MYG_home_course"
        case .tipsCircle:
            return "MYG_home_tipsCircle"
        case .profeInfo:
            return "MYG_home_profeInfo"
        case .profeTeam:
            return "MYG_home_profeTeam"
        case .find:
            return "MYG_home_find"
        case .project:
            return "MYG_home_projectManage"
        case .patient:
            return "MYG_home_patientNanage"
        case .clinTry:
            return "MYG_home_clinTry"
        case .docu:
            return "MYG_home_docufind"
        case .report:
            return "MYG_home_myReport"
        case .vitae:
            return "MYG_home_vitae"
        case .more:
            return "MYG_home_ask"
        }
    }
    
    var action: (()->Void)? {
        switch self {
        case .find:return{
            let vc = MYGFindController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .vitae:return{
            let vc = MYGResumeViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .report:return{
            if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
                let vc = MYGBaseInfoController()
    //            vc.model = model
                UIViewController.currentViewController?.navigationController?.pushViewController(vc)
                return
            }
            let vc = MYGMyReportsNewViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .medical:return{
            let vc = MYGMedicalToolsHomeController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .tipsCircle:return{
            let vc = MYGTopicViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .profeInfo:return{
            let vc = MYGIndInfoViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .patient:return{
            let phone = MYGUserManager.getUser()?.doctor.phone ?? 0
            MMYGNetwork<MYGMicrosrationApi,MYGUserDoctor>.request(target: .get_doctor_phone_info(phone: "\(phone)")) { model  in
                MYGLoading.hide()
                guard let item = model else {return}
                
                let user = MYGUserManager.getUser()
                user?.doctor = item
                MYGUserManager.saveUser(user!)
                if ((MYGUserManager.getUser()?.doctor.name.isEmpty) == true) || MYGUserManager.getUser()?.doctor.gender == 0 || ((MYGUserManager.getUser()?.doctor.identity.isEmpty) == true) {
                    let vc = MYGBaseInfoController()
        //            vc.model = model
                    UIViewController.currentViewController?.navigationController?.pushViewController(vc)
                    return
                }
                if MYGUserManager.isDoctorInfComplete  {
                    if MYGUserManager.getUser()?.doctor.status == 20 {
                        let vc = MYGPatientListViewController()
                        UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
                    }else {
                        MMYGHUD.showToast(text: "正在审核中，暂时无法使用该功能")
                    }
            
                }else {
                    let vc = MYGUpdateInfoViewController()
                    vc.model = MYGUserManager.getUser()!
                    vc.isEdit = true
                    UIViewController.currentViewController?.navigationController?.pushViewController(vc)
                }
                
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
            
           
        }
        case .more:return{
//            MYGCommunityManager.shareManager.enterCommnity() isFirstEnterCommunity MYGCommunityRecommendController
//            let vc = MYGAnswerViewViewController()
//            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
            MYGCommunityManager.shareManager.enterCommnity()
        }
        case .operation:return{
            let vc = MYGSurgicalHistoryViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case.bodyImage:return{
            let vc = MYGSelectUserController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case.clouldDisk:return{
            let vc = MYCloudDiskViewController()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .study:return{
            let vc = MYGAcademicConferenceVC()
            UIViewController.currentViewController?.navigationController?.pushViewController(vc, animated: true)
        }
        case .clinTry:return{
            let vc = H5ViewController()
            vc.title = "临床实验"
            let token = MYGUserManager.getUser()?.verification_token ?? ""
            vc.url = "http://h5-dev.medataplus.com/#/pages/clinicalDetail/clinicalDetail?token=\(token)"
            UIViewController.currentViewController?.navigationController?.pushViewController(vc)
        }
        case .docu:return{
            let vc = H5ViewController()
            vc.title = "文献查询"
            vc.url = "https://www.peipusci.com/sci?type=27"
            UIViewController.currentViewController?.navigationController?.pushViewController(vc)
        }
            
        default:
            break
        }
        
        return nil
    }
}

extension MYGHomeToolsType: Decodable, Encodable {
    
}

class MYGToolsViewController: MYGBaseController {
    // MARK: - Property
//    private var allTypes: [MYGHomeToolsType] = [, ,,]
    
//    private var toolsBase: [MYGHomeToolsType] = [.bodyImage, .operation, .teamManage, .medical, .addmi, .level]
//    private var communicateBase: [MYGHomeToolsType] = [.study, .course, .tipsCircle, .profeInfo,.profeTeam,.find]
//    private var supportBase: [MYGHomeToolsType] = [.project,.patient,.clinTry,.docu]
//    private var personalBase: [MYGHomeToolsType] = [.report,.vitae]
//    private var askBase: [MYGHomeToolsType] = [.more]
    
    private var toolsBase: [MYGHomeToolsType] = [.bodyImage, .operation, .medical, .clouldDisk]
    private var communicateBase: [MYGHomeToolsType] = [.study, .tipsCircle, .profeInfo,.find]
    private var supportBase: [MYGHomeToolsType] = [.patient,.clinTry,.docu]
    private var personalBase: [MYGHomeToolsType] = [.report,.vitae]
    private var askBase: [MYGHomeToolsType] = [.more]
    
    
    private var home: [MYGHomeToolsType] = []
    private var tools: [MYGHomeToolsType] = []
    private var communicate: [MYGHomeToolsType] = []
    private var support: [MYGHomeToolsType] = []
    private var personal: [MYGHomeToolsType] = []
    private var asks: [MYGHomeToolsType] = []

    private var contents:[MYGHomeToolsSeciton] = []
    
    private var isEdit: Bool = false {
        didSet {
            if isEdit == oldValue {
                return
            }
            //self.navigationItem.rightBarButtonItem = isEdit ? nil : UIBarButtonItem(customView: editButton)
            self.editView.isHidden = !isEdit
            
            collectionView.reloadData()
        }
    }
    
    private var moveView: UIView?
    private var moveIndex: IndexPath?
    
    private var sortDictionary: [String: [Int]] {
        get {
            let dic = UserDefaults.standard.value(forKey: "HomeSortDefalut") as? [String: [Int]] ?? [:]
            return dic
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "HomeSortDefalut")
            UserDefaults.standard.synchronize()
            NotificationCenter.default.post(name: NSNotification.Name.init("HomeSortChange"), object: nil)
        }
    }
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarShow()
        configUI()
        getSort()
        collectionView.reloadData()
    }
    
    // MARK: - 配置Cell
    private func getSort() {
        if let array = sortDictionary["home"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            home = array
        } else {
            home = [.bodyImage, .operation, .medical,.study]
        }
        
        if let array = sortDictionary["tools"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            tools = array
        } else {
            tools = toolsBase.filter{!home.contains($0)}
        }
        if let array = sortDictionary["communicate"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            communicate = array
        } else {
            communicate = communicateBase.filter{!home.contains($0)}
        }
        if let array = sortDictionary["support"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            support = array
        } else {
            support = supportBase.filter{!home.contains($0)}
        }
        if let array = sortDictionary["personal"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            personal = array
        } else {
            personal = personalBase.filter{!home.contains($0)}
        }
        if let array = sortDictionary["ask"]?.map({MYGHomeToolsType(rawValue: $0) ?? .profeTeam}) as? [MYGHomeToolsType] {
            asks = array
        } else {
            asks = askBase.filter{!home.contains($0)}
        }
        configItem()
    }
    
    private func configItem() {
        contents = []
        
        var homeSeciton = MYGHomeToolsSeciton(name: "我的工具")
        homeSeciton.items = home.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: true)
            
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.home.firstIndex(of: item.type)
                self.home = self.home.removeAll(item.type)
                if self.toolsBase.contains(item.type){
                    self.tools.append(item.type)
                }else if self.communicateBase.contains(item.type){
                    self.communicate.append(item.type)
                }else if self.supportBase.contains(item.type){
                    self.support.append(item.type)
                }else if self.personalBase.contains(item.type){
                    self.personal.append(item.type)
                }else if self.askBase.contains(item.type){
                    self.asks.append(item.type)
                }
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 0), to: IndexPath(row: self.tools.count-1, section: 1))
                self.collectionView.reloadItems(at: [IndexPath(row: self.tools.count-1, section: 1)])
            }
            return item
        })
        
        contents.append(homeSeciton)
        
        var moreSeciton = MYGHomeToolsSeciton(name: "效率工具")
        moreSeciton.items = tools.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: false)
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.tools.firstIndex(of: item.type)
                self.tools = self.tools.removeAll(item.type)
                self.home.append(item.type)
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 1), to: IndexPath(row: self.home.count-1, section: 0))
                self.collectionView.reloadItems(at: [IndexPath(row: self.home.count-1, section: 0)])
            }
            return item
        })
        contents.append(moreSeciton)
        
        var commuSeciton = MYGHomeToolsSeciton(name: "行业交流")
        commuSeciton.items = communicate.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: false)
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.communicate.firstIndex(of: item.type)
                self.communicate = self.communicate.removeAll(item.type)
                self.home.append(item.type)
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 2), to: IndexPath(row: self.home.count-1, section: 0))
                self.collectionView.reloadItems(at: [IndexPath(row: self.home.count-1, section: 0)])
            }
            return item
        })
        contents.append(commuSeciton)
        
        var supportSeciton = MYGHomeToolsSeciton(name: "科研支持")
        supportSeciton.items = support.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: false)
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.support.firstIndex(of: item.type)
                self.support = self.support.removeAll(item.type)
                self.home.append(item.type)
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 3), to: IndexPath(row: self.home.count-1, section: 0))
                self.collectionView.reloadItems(at: [IndexPath(row: self.home.count-1, section: 0)])
            }
            return item
        })
        contents.append(supportSeciton)
        
        var personalSeciton = MYGHomeToolsSeciton(name: "个人成长")
        personalSeciton.items = personal.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: false)
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.personal.firstIndex(of: item.type)
                self.personal = self.personal.removeAll(item.type)
                self.home.append(item.type)
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 4), to: IndexPath(row: self.home.count-1, section: 0))
                self.collectionView.reloadItems(at: [IndexPath(row: self.home.count-1, section: 0)])
            }
            return item
        })
        contents.append(personalSeciton)
        
        var askSeciton = MYGHomeToolsSeciton(name: "更多")
        askSeciton.items = asks.map({ type in
            var item = MYGHomeToolsItem(type: type, isHome: false)
            item.changeAction = {[weak self] in
                guard let self = self else {
                    return
                }
                let index = self.asks.firstIndex(of: item.type)
                self.asks = self.asks.removeAll(item.type)
                self.home.append(item.type)
                
                self.configItem()
                self.collectionView.moveItem(at: IndexPath(row: index ?? 0, section: 4), to: IndexPath(row: self.home.count-1, section: 0))
                self.collectionView.reloadItems(at: [IndexPath(row: self.home.count-1, section: 0)])
            }
            return item
        })
        contents.append(askSeciton)
        
    }
    
    // MARK: - UI
    private func configUI() {
        title = "首页更多"
        //self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editButton)
        
//        view.addSubview(stackView)
//        editView.addSubviews([hintLabel, cancelButton, saveButton])
//        stackView.addArrangedSubviews([editView, collectionView])
        
//        stackView.snp.makeConstraints { make in
//            make.left.right.bottom.equalToSuperview()
//            make.top.equalToSuperview().offset(statusBarHeight+navHeight)
//        }
        view.addSubview(hintLabel)
      
        //view.addSubview(editView)
        view.addSubview(collectionView)
//        editView.snp.makeConstraints { make in
//            make.height.equalTo(39)
//            make.left.right.equalToSuperview()
//            make.top.equalToSuperview().offset(statusBarHeight+navHeight)
//        }
        collectionView.snp.makeConstraints { make in
//            make.height.equalTo(1000)
            make.left.right.top.bottom.equalToSuperview()
            //make.top.equalTo(editView.snp.bottom)
        }
        
      
        
//        hintLabel.snp.makeConstraints { make in
//            make.left.equalToSuperview().offset(22)
//            make.centerY.equalTo(cancelButton)
//        }
//        

        cancelButton.isHidden = true
        //saveButton.isHidden = true
        
    }
    
    // MARK: - lazy load
    private lazy var editButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("编辑", for: .normal)
        btn.setTitle("保存", for: .selected)
        btn.setTitleColor(.rgba(44, 44, 44,1), for: .normal)
        btn.titleLabel?.font = .regular(11)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    private lazy var stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        return stackView
    }()
    
    private lazy var editView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    private lazy var hintLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(13)
        label.textColor = .rgba(56, 56, 56, 1)
        label.text = "拖动可调整应用位置"
        return label
    }()
    
    private lazy var cancelButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消", for: .normal)
        btn.setTitleColor(.rgba(44, 44, 44, 1), for: .normal)
        btn.titleLabel?.font = .regular(11)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
//    private lazy var saveButton: UIButton = {
//        let btn = UIButton()
//        btn.setTitle("保存", for: .normal)
//        btn.setTitleColor(.rgba(44, 44, 44, 1), for: .normal)
//        btn.titleLabel?.font = .regular(11)
//        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
//        return btn
//    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: screenWidth/4, height: 96)
        layout.minimumLineSpacing = 4
        layout.minimumInteritemSpacing = 0
        layout.headerReferenceSize = CGSize(width: screenWidth, height: 47)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: MYGToolsCollectionViewCell.self)
        cv.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: MYGToolsCollectionReusableView.self)
        
//        let ges = UIPanGestureRecognizer(target: self, action: #selector(panGesture))
//        cv.isUserInteractionEnabled = true
//        ges.delegate = self
//        cv.addGestureRecognizer(ges)
        return cv
    }()
}

extension MYGToolsViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents[section].items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: MYGToolsCollectionViewCell.self, for: indexPath)
        cell.model = contents[indexPath.section].items[indexPath.row]
        cell.editButton.isHidden = !isEdit
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: MYGToolsCollectionReusableView.self, for: indexPath)
        let name = contents[indexPath.section].name
        view.nameLabel.text = name
        if indexPath.section == 0 {
            
            view.addSubview(editButton)
            view.addSubview(cancelButton)
            editButton.snp.makeConstraints { make in
                make.right.equalToSuperview().inset(23)
                make.bottom.equalToSuperview()
                make.width.equalTo(56)
                make.height.equalTo(25)
            }
            cancelButton.snp.makeConstraints { make in
                make.right.equalTo(editButton.snp.left).offset(-11)
                make.bottom.equalToSuperview()
                make.width.equalTo(56)
                make.height.equalTo(25)
            }
        }else {
            view.subviews.forEach { v in
                if v is UIButton {
                    v.removeFromSuperview()
                }
            }
        }
        
        return view
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if isEdit {
            return
        }
        contents[indexPath.section].items[indexPath.row].action?()
    }
    
  
    
}

extension MYGToolsViewController: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
       
        if ((gestureRecognizer.view?.isKind(of: UIScrollView.self)) != nil) {
            return true
        }
        
        return false
    }
    
}
extension MYGToolsViewController {
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == cancelButton {
            self.isEdit = false
            getSort()
            collectionView.reloadData()
            self.cancelButton.isHidden = true
            self.editButton.isSelected = false
        }
        
        if btn == editButton {
            if editButton.isSelected == true && home.count < 4 {
                MMYGHUD.showToast(text: "至少选择4项")
                return
            }
            btn.isSelected = !btn.isSelected
            self.isEdit = btn.isSelected
            self.cancelButton.isHidden = !self.isEdit
            if self.isEdit == false  {
                let dic = [
                    "home": home.map{$0.rawValue},
                    "tools": tools.map{$0.rawValue},
                    "communicate": communicate.map{$0.rawValue},
                    "support": support.map{$0.rawValue},
                    "personal": personal.map{$0.rawValue},
                ]
                sortDictionary = dic
            }
        }
        
    }
    
    @objc
    private func panGesture(_ gesture: UIPanGestureRecognizer) {
        guard isEdit else {
            return
        }
        
        let point = gesture.location(in: gesture.view)
        
        switch gesture.state {
        case .began:
            starPress(point: point)
        case .changed:
            movePress(point: point)
        case .ended:
            endPress()
        default:
            break
        }
    }
    
    private func starPress(point: CGPoint) {
        guard let index = collectionView.indexPathForItem(at: point), let cell = collectionView.cellForItem(at: index) else {
            return
        }
        
        guard let view = cell.snapshotView(afterScreenUpdates: true) else {
            return
        }
        
        let offsetPonit = CGPoint(x: point.x, y: point.y+statusBarHeight+navHeight)
        
        
        self.moveView = view
        self.moveIndex = index
        
        self.view.addSubview(view)
        view.center = offsetPonit
        cell.isHidden = true
    }
    
    private func movePress(point: CGPoint) {
        let offsetPonit = CGPoint(x: point.x, y: point.y)
        self.moveView?.center = offsetPonit
        
        guard let newIndex = collectionView.indexPathForItem(at: point), let index = moveIndex, newIndex != index && newIndex.section == 0 else {
            return
        }
        
        let type = contents[index.section].items[index.row].type
        home = home.removeAll(type)
        if self.tools.contains(type){
            tools = tools.removeAll(type)
        }else if self.communicate.contains(type){
            communicate = communicate.removeAll(type)
        }else if self.support.contains(type){
            support = support.removeAll(type)
        }else if self.personal.contains(type){
            personal = personal.removeAll(type)
        }
        if newIndex.section == 0 {
            home.insert(type, at: newIndex.row)
        }else if newIndex.section == 1 {
            tools.insert(type, at: newIndex.row)
        }else if newIndex.section == 2 {
            communicate.insert(type, at: newIndex.row)
        }else if newIndex.section == 3 {
            support.insert(type, at: newIndex.row)
        }else if newIndex.section == 4 {
            personal.insert(type, at: newIndex.row)
        }
        
        print("home: \(home.count)-------\nmore: \(tools.count)-------\nindex: \(index)-------new:\(newIndex)")
        
        configItem()
        collectionView.moveItem(at: index, to: newIndex)
        moveIndex = newIndex
    }
    
    private func endPress() {
        self.moveView?.removeFromSuperview()
        if let moveIndex = moveIndex, let cell = collectionView.cellForItem(at: moveIndex) {
            cell.isHidden = false
            collectionView.reloadItems(at: [moveIndex])
        }
        
        self.moveView = nil
        self.moveIndex = nil
    }
}
